<?php
/*
---------------------------------------------------------
														+
名称:易通支付通道										+
														+
控制器名称:YiTongController								+
														+
日期:2017-10-11											+
														+
作者:小翁												+
														+
---------------------------------------------------------
*/
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

class GelinController extends PayController{
    protected $config;
    protected $key;
    protected $url;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array) {
        $this->config = Channel::getInstance()->getById($array['channel']);
        if (!$this->config) {
            $this->showmessage('通道错误!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode", 0, "intval"));
        if (!$product) {
            $this->showmessage('未找到支付产品!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel' => $array
        );

        $return = $this->orderadd($parameter);

        $pay_memberid = $this->config['mch_id'];   //商户ID
        $pay_orderid = $return['orderid'];
        $pay_applydate = date("Y-m-d H:i:s", time());  //订单时间

        switch ($this->config['paytype']) {
            //支付宝
            case 3:
            case 4:
            case 17:
            case 18:
                $pay_service = '903';
                break;
            default:
                $this->showmessage('不支持此产品!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        $pay_notifyurl = $return['notifyurl'];
        $pay_callbackurl = $return['callbackurl'];
        $pay_amount = number_format($return['amount'], 2, '.', '');

        $Md5key = $this->config['signkey'];  //密钥

        $jsapi = array(
            "pay_memberid" => $pay_memberid,
            "pay_orderid" => $pay_orderid,
            "pay_amount" => $pay_amount,
            "pay_applydate" => $pay_applydate,
            "pay_service" => $pay_service,
            "pay_notifyurl" => $pay_notifyurl,
            "pay_callbackurl" => $pay_callbackurl,
        );

        ksort($jsapi);

        $md5str = "";
        foreach ($jsapi as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }

        $sign = strtoupper(md5($md5str . "key=" . $Md5key));


        $jsapi["pay_md5sign"] = $sign;
        $jsapi["pay_attach"] = 'zf';
        $jsapi["pay_productname"] = 'zf';

        $res = curl($this->config['gateway'], httpstr($jsapi));

        $res = json_decode($res, true);

        if ($res['status'] !== 'success') {
            if ($res['msg']) {
                $this->showmessage($res['msg'], ['code' => C("THIRDCODES." . $this->class)]);
            }

            $this->showmessage('获取支付链接失败!', ['code' => C("THIRDCODES." . $this->class)]);
        }

        $code = $res['data'];

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
                if(isMobile()){
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            //支付宝
            case 17:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 18:
                $this->display("WeiXin/alipay");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true."\r\n\r\n"), FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date('Y-m-d H:i:s',time())."\r\n\r\n", FILE_APPEND);

        $p = I("post.");
        /*$p = array (
            'memberid' => '10095',
            'orderid' => '2018122019074624520',
            'transaction_id' => '20181220190746509710255910095',
            'amount' => '10.0000',
            'datetime' => '20181220190800',
            'returncode' => '00',
            'sign' => 'B5EADD18EA5BF2E3ACBC3E80B108B938',
            'attach' => 'zf',
        );*/

        //获取订单信息
        $orderid = $p['orderid'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();

        if(!$find){
            echo 'order_not_found'; exit;
        }
        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$p['busi_order_no']))->save(array("server_return"=> json_encode($p),"pay_orderid_rd"=>$p['transaction_id']));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $ReturnArray = array( // 返回字段
            "memberid" => $p["memberid"], // 商户ID
            "orderid" =>  $p["orderid"], // 订单号
            'transaction_id' => $p["transaction_id"],
            "amount" =>  $p["amount"], // 交易金额
            "datetime" =>  $p["datetime"], // 交易时间
            "returncode" => $p["returncode"]
        );

        $key = $this->config['signkey'];

        ksort($ReturnArray);

        $str = "";
        foreach ($ReturnArray as $k => $v) {
            $str .= $k."=".$v."&";
        }
        $str .= "key=".$key;

        $sign = $p['sign'];
        $sign2 = strtoupper(md5($str));

        if($sign != $sign2){
            exit("sign_wrong");
        }
        if($p['returncode'] != '00'){
            exit("pay_fail");
        }

        //处理支付
        //$this->EditMoney($find['pay_orderid'],"Yifa",0);

        //回调成功
        //echo 'ok'; exit;
        $this->async($find['pay_orderid'],'ok');
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }
}